var app=sm("do_App");
var page=sm("do_Page");
var nf=sm("do_Notification");
var global=sm("do_Global");
var cache = sm("do_DataCache");
var config = require("config");
var algorithm=sm("do_Algorithm");
var storage=sm("do_Storage");

var do_ALayout_root=ui("do_ALayout_root");
var do_loginbtn=ui("do_loginbtn");
var do_username = ui("do_username");
var do_password = ui("do_password");

do_ALayout_root.on("touch",function(){
	page.hideKeyboard();
});

page.on("back", function(){
     global.exit();
});
page.on("loaded",function(){	
	var username=cache.loadData("username");
	if(username){
		do_username.text=username;
	}	
});
//用于等待登录的过程
do_ALayout_root.add("loadingUI", "source://view/loadingUI.ui", 0, 0);
var loadingUI = ui("loadingUI");
//初始化隐藏遮盖
loadingUI.visible = false;

var olddate=0;
var pagesize=1;
var do_timer=mm("do_Timer");
do_timer.interval = 10*1000;
app.on("tologin",function(data){
	olddate=data.times;
	pagesize=data.pagesize;
});
do_timer.on("tick",function(){
	var nowdate=new Date();
	var nowtime=nowdate.getTime();
	if((nowtime-olddate)>=5*60*1000){
		this.stop();
		app.closePage({data:"登录失效,请重新登录", animationType:"", layer:pagesize});	
		cache.saveData("userinfo", "");
	}

});

do_loginbtn.on("touch", function() {
	page.hideKeyboard();
	var username = do_username.text;
	if (!username) {                      
		nf.toast("帐号不可为空");
		return;
	}
	var pwd = do_password.text;
	if (!pwd) {
		 nf.toast("密码不可为空");
		 return;
	}
	loadingUI.visible = true;
	do_loginbtn.enabled = false;
	
	var password=algorithm.base64Sync({type:"encode",source:pwd});
	var usernum=Math.floor(Math.random()*1000);
	var http = mm("do_Http");	
	http.method = "POST";
	http.timeout = 10 * 1000;
	http.contentType = "application/json";
	http.url = config.baseUrl + "login";
	http.body=JSON.stringify({username:username+","+page.getData(),userpwd:password,usernum:usernum});
	http.on("success", function(data) {		
		
		loadingUI.visible = false;	
		do_loginbtn.enabled=true;
		if(data && data.result==1){	
			data.data.usernum=usernum;
			cache.saveData("userinfo", data.data);
			cache.saveData("username", username);
			var nowdate=new Date();
			olddate=nowdate.getTime();	
			pagesize=1;
			do_timer.start();
				app.openPage({
					source:"source://view/index.ui", 
					animationType:'push_r2l'
						});
				 do_password.text="";		
		}		
		else{
			nf.toast(data.msg || "登录失败"); 
		}
	});
	http.on("fail", function(data) {
		loadingUI.visible = false;
		do_loginbtn.enabled = true;
		nf.toast("网络异常");
	});
	http.request();
}).on("touchDown", function(){
	do_loginbtn.bgColor = "262626FF";	
}).on("touchUp",function(){
	do_loginbtn.bgColor = "333333FF";
});
page.on("result",function(result){
	do_timer.stop();
	if(result) nf.toast(result);
});